#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import io
import sys
import zipfile


def delimited(file, grep, delimiter='\n', bufsize=4096):
    buf = ''
    bufsize_tmp = bufsize
    while True:
        newbuf = file.read(bufsize_tmp)
        if not newbuf:
            yield buf
            return
        #if newbuf
        if type(newbuf) is  bytes:
            try:
                newbuf = newbuf.decode("utf-8","backslashreplace")
            except:
                newbuf = str(newbuf)
        buf += newbuf
        lines = buf.split(delimiter)
        buf = lines[-1]
        if grep and greps(lines, grep):
            continue
        for line in lines[:-1]:
            yield line
        #our_input = input()
        #if our_input == '\r':
        #    continue
        #elif our_input == 'c':
        #    return
        #elif our_input == 'b':
        #    bufsize_tmp = bufsize_tmp * 2


def greps(lines, grep):
    for line in lines[:-1]:
        if line.find(grep) >= 0:
            print(line.replace('', '|'))
            return False
    return True

def replaceSupportZip(fileName, grep):
    if fileName.endswith(".zip"):
        zip_file = zipfile.ZipFile(fileName)
        for name in zip_file.namelist():
            with zip_file.open(name, 'r') as f:
                replace(f, grep)
    else:
        with io.open(fileName, 'r', encoding='utf-8') as f:
            replace(f,grep)


def replace(f, grep):
        count =0
        lines = delimited(f, grep, '', bufsize=1024)
        for line in lines:
            if line:
                count=count+1
            if grep is None and line:
                print(line.replace('', '|'))
        print("-------- count: "+str(count))

# param = sys.argv[1]
# param ='F:\\FULL_CON_TICKETINFO20210423181514055_0_001.txt'

if len(sys.argv) > 1 and sys.argv[1]:
    grep = None
    if len(sys.argv) > 2 :
        grep = sys.argv[2]
    
    if '*' in sys.argv[1] :
        path = sys.argv[1][:sys.argv[1].find('\\')+1]
        stars = sys.argv[1][sys.argv[1].find('\\')+1:]
        files = os.listdir(path)
        for fileName in files:
            if stars.endswith('*') and fileName.startswith(stars[stars.find('*'):]) :
                print(fileName)
                replaceSupportZip(path+fileName,grep)
            elif stars.startswith('*') and fileName.endswith(stars[stars.find('*'):]) :
                print(fileName)
                replaceSupportZip(path+fileName,grep)
            else:
                s=stars.split('*')
                if fileName.startswith(s[0]) and fileName.endswith(s[1]):
                    print(fileName)
                    replaceSupportZip(path+fileName,grep)
        exit()

    if len(sys.argv) > 1:
        replaceSupportZip(sys.argv[1],grep)
    



# python splitFile.py F:\\FULL_T_CMP_TYPE_RECHARGELIST20210423194339515_1_001.txt  1234
